﻿using System;
using System.Web.Http;
using SimpleInjector;
using Sustainalytics.Claims.BL;
using Sustainalytics.Caching;
using Sustainalytics.Entities;
using Sustainalytics.DataLayer;
using System.Configuration.Abstractions;

namespace Sustainalytics.Claims.Service
{
    public static class CompositionRoot
    {
    
        public static Container RegisterDependencies(HttpConfiguration config)
        {
            var container = new Container();
            var clientPlatformConnectionString = ConfigurationManager.Instance.ConnectionStrings["ClientPlatform"].ConnectionString;

            container.Options.DefaultScopedLifestyle = new SimpleInjector.Lifestyles.AsyncScopedLifestyle();
            container.RegisterWebApiControllers(config);

            container.RegisterMisc();

            container.RegisterRepositories(clientPlatformConnectionString);

            container.RegisterBussinessLogic();

            container.Verify();
            return container;
        }


        private static void RegisterRepositories(this Container container,
           string clientPlatformConnectionString)
        {
            container.Register(typeof(IAccountsRepository), () => AccountsRepository.GetAccountsRepository(clientPlatformConnectionString));
        }

        private static void RegisterBussinessLogic(this Container container)
        {
            container.Register(typeof(IOperationClaimsRetriever), ()=>new OperationClaimsRetriever(container.GetInstance< IClaimsL1Cache>()));
        }

        private static void RegisterMisc(this Container container)
        {

            container.RegisterSingleton(typeof(IClaimsChecker), ()=> new ClaimsChecker());
            container.RegisterSingleton(typeof(IClaimMapComparer), () => new ClaimMapComparer());
            container.RegisterSingleton(typeof(IUserMapComparer), () => new UserMapComparer());
            container.RegisterSingleton(typeof(IClaimsL2Cache), () => new ClaimsL2Cache());
            container.RegisterSingleton(typeof(IAppCache), () => new AppMemoryCache());
            container.RegisterSingleton(typeof(IClaimsL1Cache), () => new ClaimsL1Cache(container.GetInstance<IAppCache>(), 
            container.GetInstance<IClaimsL2Cache>(), container.GetInstance<IClaimMapComparer>(), container.GetInstance<IUserMapComparer>()));

        }
    }
}
